﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model.Enum.UserEnum;

namespace BLL.Manage
{
    public class UserManage
    {
        public Model.Basics.UserModel.UserTokenModel UserTokenModel;

        public UserManage()
        {
            this.GetUserInfoByToken();
        }


        public Model.Basics.UserModel.UserTokenModel GetUserInfoByToken(string token = null)
        {
            var httpContext = Utils.HttpContextClass.ServiceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext;
            var accessToken = (token == null ? httpContext.Request.Headers["accessToken"].ToString() : token);
            if (!string.IsNullOrEmpty(accessToken))
            {
                var find = RedisHelper.HashService.HashGet<Model.Basics.UserModel.UserTokenModel>(Model.Enum.Basics.RedisEnum.token.ToString(), accessToken);
                this.UserTokenModel = find;
                return find;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="userPwd"></param>
        /// <returns></returns>
        public Model.Result<Model.ApiResult.UserResult.UserLoginResult> UserLogin(string userId, string userPwd)
        {
            using (Model.Entity.DBContext context = new Model.Entity.DBContext())
            {
                var user = context.User.SingleOrDefault(p => p.UserId == userId && p.UserPwd == userPwd);
                if (user == null)
                {
                    return new Model.Result<Model.ApiResult.UserResult.UserLoginResult>()
                    {
                        Code = 500,
                        Data = null,
                        Message = "账号或密码错误",
                    };
                }
                else
                {
                    var accessToken = System.Guid.NewGuid().ToString();
                    var httpContext = Utils.HttpContextClass.ServiceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext;
                    var equipment = (httpContext.Request.Headers["platform"] == "mobile" ? EquipmentEnum.pc : EquipmentEnum.mobile);
                    // 查找是否在其他地方登陆  通过用户ID和平台来查询
                    var find = RedisHelper.HashService.HashGetAll<Model.Basics.UserModel.UserTokenModel>(Model.Enum.Basics.RedisEnum.token.ToString());

                    var findItem = find
                        .FirstOrDefault(p => p.Value.MemberId == user.MemberId && p.Value.EquipmentEnum == equipment);
                    if (findItem.Value != null)
                    {
                        // 找到了 就删除 完成单平台的单点登陆
                        RedisHelper.HashService.HashDelete(Model.Enum.Basics.RedisEnum.token.ToString(), findItem.Key);
                    }
                    // token实体
                    var tokenModel = new Model.Basics.UserModel.UserTokenModel()
                    {
                        AccessToken = accessToken,
                        EquipmentEnum = httpContext.Request.Headers["platform"] == "mobile" ? EquipmentEnum.pc : EquipmentEnum.mobile,
                        MemberId = user.MemberId
                    };
                    // 添加到REDIS中
                    RedisHelper.HashService.HashSet<Model.Basics.UserModel.UserTokenModel>(Model.Enum.Basics.RedisEnum.token.ToString(), accessToken, tokenModel);
                    return new Model.Result<Model.ApiResult.UserResult.UserLoginResult>()
                    {
                        Code = 0,
                        Data = new Model.ApiResult.UserResult.UserLoginResult()
                        {
                            AccessToken = accessToken,
                            Avatar = user.Avatar == null ? "" : user.Avatar,
                            MemberId = user.MemberId,
                            NickName = user.NickName
                        },
                        Message = "登录成功",
                    };
                }
            }
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        public Model.ApiResult.UserResult.UserInfoResult GetUserInfo()
        {
            using (Model.Entity.DBContext context = new Model.Entity.DBContext())
            {
                if (this.UserTokenModel != null)
                {
                    var userInfo = context.User.FirstOrDefault(p => p.MemberId == this.UserTokenModel.MemberId);
                    if (userInfo != null)
                    {
                        return new Model.ApiResult.UserResult.UserInfoResult()
                        {
                            NickName = userInfo.NickName,
                            Avatar = userInfo.Avatar,
                            MemberId = userInfo.MemberId
                        };
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }
        }
    }
}
